'use strict'
const axios = require('axios')

const Service = require('egg').Service

const UserModel = require('../../models/user')

class UserService extends Service {
  userModel = UserModel(this.app.model)

  async loginByToken(userId) {
    const { app } = this
    const token = await app.jwt.sign({ userId }, app.config.jwt.secret, {
      expiresIn: app.config.tokenFailureTime,
    })
    return token
  }

  async login(code) {
    const { ctx, app } = this
    try {
      const { WX_APPID, WX_SECRET } = app.config
      const { data } = await axios.get(
        `https://api.weixin.qq.com/sns/jscode2session?appid=${WX_APPID}&secret=${WX_SECRET}&js_code=${code}&grant_type=authorization_code`
      )

      if (data.errcode) {
        return ctx.failure(data.errmsg)
      }

      const openid = data.openid
      // 查询数据库 openid 是否存在
      const where = {
        open_id: openid,
      }

      // 执行查询
      const items = await this.userModel.findAll({
        where,
        attributes: {
          include: [...Object.keys(this.userModel.rawAttributes)],
          exclude: [],
        },
      })

      // 判断查询结果是否为空
      if (items.length === 0) {
        // 为空新建用户
        const transaction = await app.model.transaction() // 启用事务

        try {
          const record = {
            id: ctx.helper.generateId(),
            name: '新用户',
            open_id: openid,
            union_id: ctx.helper.generateId(),
          }

          await this.userModel.create(record, { transaction })
          await transaction.commit()
          const token = await this.loginByToken(openid)
          ctx.success('查询成功', token)
        } catch (error) {
          await transaction.rollback() // 回滚事务
          ctx.failure(`查询失败:${error}`)
        }
      } else {
        // 处理结果
        // const processedItems = items.map(item => {
        //   const obj = item.toJSON()
        //   Object.keys(obj).forEach(key => obj[key] === null && delete obj[key])
        //   return obj
        // })
        const token = await this.loginByToken(openid, )
        ctx.success('查询成功', token)
      }
    } catch (error) {
      ctx.failure(`查询失败:${error}`)
    }
  }
}

module.exports = UserService
